import { FC, useEffect } from "react";
import { Form, Input, Button, Checkbox, Card, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import styles from "./index.module.less";
import { LoginData, login } from "@/api";
import { useDispatch, useSelector } from "react-redux";
import { setTokens } from "@/store/modules/user";
import { RootState } from "@/store";
import { useNavigate } from "react-router-dom";
interface LoginForm {
  username: string;
  password: string;
  remember: boolean;
}

const Login: FC = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const token = useSelector((state:RootState)=>state.user.token)
  useEffect(()=>{
    if(token) {
      navigate("/")
      message.success("登陆成功",1)
    }
  },[navigate, token])
  const onFinish = async (values: LoginForm) => {
    const res = await login(values as LoginData)
    dispatch(setTokens(res.data.token))
  };

  return (
    <div className={styles.loginContainer}>
      <Card className={styles.card}>
        <div className={styles.loginHeader}>
          <h1 style={{ textAlign: "center" }}>电商后台管理系统</h1>
        </div>
        <Form
          name="login"
          initialValues={{ remember: true,username:"admin",password:"123456" }}
          onFinish={onFinish}
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名！" }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码！" }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              allowClear
            />
          </Form.Item>

          <Form.Item>
            <div className={styles.loginOptions}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
            </div>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
